﻿using System;
using System.Collections.Generic;
using System.Text;
using Castle.ActiveRecord;
using NHibernate.Expression;

namespace MyMessenger.Core.Services.Impl
{
    public class UserService : IUserService
    {
        int userActivePeriodInMilisekond;

        public UserService() : this(5000)
        {
        }

        public UserService(int userActivePeriodInMilisekond)
        {
            this.userActivePeriodInMilisekond = userActivePeriodInMilisekond;
        }

        public void Save(User u)
        {
            ActiveRecordMediator<User>.SaveAndFlush(u);            
        }

        public User Find(int id)
        {
            return ActiveRecordMediator<User>.FindByPrimaryKey(id, false);
        }

        public User Find(string name)
        {
            return ActiveRecordMediator<User>.FindFirst(Expression.Eq("Name", name));
        }

        public User[] FindAll()
        {
            return ActiveRecordMediator<User>.FindAll();
        }

        public User[] ActiveUsers()
        {
            DetachedCriteria crit = DetachedCriteria.For<User>();
            crit.Add(Expression.Ge("ConnectedTime", DateTime.Now.AddMilliseconds(-userActivePeriodInMilisekond)));
            return ActiveRecordMediator<User>.FindAll(crit, Order.Asc("Name"));
        }

        public void MarkUserResponse(User u)
        {
            u.ConnectedTime = DateTime.Now;
            Save(u);
        }
    }
}
